package com.timkj.wxtemplatemessage.utils.log;

import com.timkj.wxtemplatemessage.config.BasicConfig;
import com.timkj.wxtemplatemessage.utils.DateUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;

/**
 * @author : liji
 * @date : 2020-10-01 11:56
 */
public class LogUtil {
    //日志文件后缀名
    private static final String address = ".log";
    private static BasicConfig basicConfig = new BasicConfig();

    public static void save(String message){
        File file = new File(dir() + "/"
                + DateUtil.getDateByString() + address);
        try {
            FileWriter fw = new FileWriter(file,true);
            fw.write(message);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String dir(){
        File file = new File(basicConfig.getLogPath());
        if(!file.exists() || !file.isDirectory()){
            file.mkdir();
        }
        return file.getPath();
    }

    public static String info(String className,String message){
        return message(LogEnums.info.toString(),className,message);
    }

    public static String info(String className,String message,Throwable throwable){
        return message(LogEnums.info.toString(),className,message,throwable);
    }

    public static String error(String className,String message){
        return message(LogEnums.error.toString(),className,message);
    }

    public static String error(String className,String message,Throwable throwable){
        return message(LogEnums.error.toString(),className,message,throwable);
    }

    private static String message(String grade,String className,String mess){
        String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        return DateUtil.getCurrentTime() + "\t" +
                grade + "\t" +
                pid + "\t" +
                " ---[" + Thread.currentThread().getName() + "]" +
                className + "\t" +
                "msg: " + mess + "\n";
    }

    private static String message(String grade,String className,String mess,Throwable throwable){
        return message(grade, className, mess) +
                "throwable: " + throwable.getMessage() + "\n";
    }
}
